import pygame

import data

def initsounds():
    pygame.mixer.set_num_channels(4)

def loadsound(filename):
    try:
        return loadsound._cache[filename]
    except KeyError:
        pass
    snd = pygame.mixer.Sound(data.load(filename))
    loadsound._cache[filename] = snd
    return snd
loadsound._cache = {}

def play_bgmusic(filename):
    'plays filename as music in the background on repeat until told to stop.'
    if pygame.mixer.music.get_busy():
        pygame.mixer.music.fadeout(100)
    pygame.mixer.music.load(data.filepath(filename))
    pygame.mixer.music.play(-1)

def play_sfx(filename):
    'plays a sound effect once only.'
    sfx = pygame.mixer.find_channel(False)
    if not sfx: return
    sound = loadsound(filename)
    sfx.play(sound)
